﻿using AntMovement.Comm.Model;
using AntMovement.Core.LabelService;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AntMovement.Comm
{
    public class AntService
    {
        private Dictionary<int, OutTimeModel> _cacheTime;
        private UdpClient _udpClient;
        private ITagManager _tagManager;
        private CancellationTokenSource _tokenSource;
        private Queue<EndPointDataModel> _queue;
        private IChainedHandle _chaine;
        private int _port;
        private string _ip;

        public AntService(ITagManager tagManager)
        {
            _port = 22345;
            _chaine = new Verify(tagManager, new Func<int, OutTimeModel>(id =>
            {
                if (_cacheTime.ContainsKey(id))
                {
                    return _cacheTime[id];
                }
                return default;
            }),
            new Func<int, bool, bool>((id, bl) =>
            {
                if (bl)
                {
                    if (_cacheTime.ContainsKey(id))
                    {
                        _cacheTime.Remove(id);
                        return true;
                    }
                    return false;
                }
                else
                {
                    if (_cacheTime.ContainsKey(id))
                    {
                        _cacheTime[id].OutTime = DateTime.Now;
                    }
                    else
                    {
                        _cacheTime.Add(id, new OutTimeModel() { Markings = id, OutTime = DateTime.Now });
                    }
                }
                return true;
            }));
            _cacheTime = new Dictionary<int, OutTimeModel>();
            _queue = new Queue<EndPointDataModel>();
            _tagManager = tagManager;
        }

        public bool Open()
        {
            if (_udpClient == null)
            {
                _tokenSource = new CancellationTokenSource();
                try
                {
                    _udpClient = new UdpClient(_port);
                    Task.Run(() => {
                        while (!_tokenSource.Token.IsCancellationRequested)
                        {
                            while (_queue.Count == 0)
                            {
                                Thread.Sleep(5);
                            }
                            EndPointDataModel endPoint = _queue.Dequeue();
                            try
                            {
                                List<byte> result = new List<byte>();
                                _chaine.Execute(endPoint.Buffer, result);
                                _udpClient.Send(result.ToArray(), result.Count, endPoint.Client);
                            }
                            catch (Exception) { }
                        }
                    });
                    Task.Run(() =>
                    {
                        while (!_tokenSource.Token.IsCancellationRequested)
                        {
                            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
                            byte[] receivedBytes = _udpClient.Receive(ref remoteEndPoint);
                            //Console.WriteLine($"IP:{remoteEndPoint.Address.ToString()} port:{remoteEndPoint.Port} data:[{BitConverter.ToString(receivedBytes)}]");
                            _queue.Enqueue(new EndPointDataModel()
                            {
                                Buffer = receivedBytes,
                                Client = remoteEndPoint,
                            });
                        }
                        try
                        {
                            _udpClient.Close();
                            _udpClient?.Dispose();
                        }
                        catch (Exception)
                        {
                        }
                    });
                }
                catch (Exception)
                {
                    return false;
                }
            }
            return true;
        }

        public void Close()
        {
            if (_udpClient != null)
            {
                try
                {
                    _tokenSource.Cancel();
                }
                catch (Exception)
                {
                }
            }
        }
    }

    public class EndPointDataModel
    {
        public byte[] Buffer { get; set; }
        public IPEndPoint Client { get; set; }
    }
}
